<!-- 基础信息 -->
<template>
    <div class="outer ">
        <el-form ref="form" :model="form" label-width="7.29vw">
            <div class="select">
                <el-form-item label="发文方式:">
                    <div class="types">
                        <div :class="{ type: true, active: type == 1 }" @click="getType(1)">
                            <i class="el-icon-picture"></i>
                            <span>图文编辑</span>
                            <img v-if="type == 1" class="rIcon" src="@/assets/img/01.png" alt="">
                        </div>
                        <div :class="{ type: true, active: type == 2 }" @click="getType(2)">
                            <i class="iconfont">&#xe8df;</i>
                            <span>文件上传</span>
                            <img v-if="type == 2" class="rIcon" src="@/assets/img/01.png" alt="">
                        </div>
                    </div>
                </el-form-item>
            </div>
            <div class="select" v-show="type != 1">
                <el-form-item label="文件上传:" required>
                    <div class="upload">
                        <label>
                            <div style="display: block;">
                                <div style="display: flex; align-items: center;">
                                    <input type="file" @change="onUpload_video">
                                    <img src="@/assets/img/icon08.png" alt="">
                                    <p>视频上传</p>
                                </div>
                                <div v-if="videoname"
                                    style="font-size: 16px; color: #808080; line-height: 20px; margin-top: 5px;">
                                    {{ videoname }}
                                </div>
                            </div>
                        </label>


                        <label>
                            <div style="display: block;">

                                <div style="display: flex;align-items: center;">
                                    <input type="file" @change="onUpload_aduio">
                                    <img src="@/assets/img/icon09.png" alt="">
                                    <p>音频上传</p>

                                </div>
                                <div v-if="audioname" style="font-size: 16px;color: #808080;line-height: 20px;">{{
                                    audioname }}</div>

                            </div>
                        </label>

                        <label>
                            <div style="display: block;">
                                <div style="display: flex; align-items: center;">
                                    <input type="file" @change="onUpload_file">
                                    <img src="@/assets/img/icon17.png" alt="">
                                    <p>文件上传</p>
                                </div>
                                <div v-if="filename"
                                    style="font-size: 16px; color: #808080; line-height: 20px; margin-top: 5px;">
                                    {{ filename }}
                                </div>
                            </div>
                        </label>

                    </div>
                </el-form-item>
            </div>
            <el-form-item label="文库标题:" required>
                <el-input v-model="form.title" placeholder="请输入文库标题"></el-input>
            </el-form-item>
            <div class="price">
                <el-form-item label="价格设置:" required>
                    <el-input-number v-model="form.price" :min="0"></el-input-number>
                </el-form-item>
            </div>
            <div class="select">
                <el-form-item label="发文专栏:" required>

                    <!-- <el-select filterable remote v-model="form.col_id" default-first-option placeholder="请输入专栏名称"
                        @change="onChange" :remote-method="getInput1" width="100px" @visible-change="isopen1">
                        <el-option v-for="item in cols" :key="item.id" :label="item.title" :value="item.id">
                        </el-option>
                        <el-option disabled class="load-more" v-if="showMore1">
                            <span @click="loadc">加载更多...</span>
                        </el-option>
                    </el-select> -->

                    <el-select :popper-append-to-body="false" filterable v-model="form.col_id" placeholder="请选择专栏">
                        <el-option v-for="item in cols" :key="item.id" :label="item.title" :value="item.id"></el-option>
                        <el-option disabled class="load-more" v-if="showMore1">
                            <span @click="loadc">加载更多...</span>
                        </el-option>
                    </el-select>
                </el-form-item>
            </div>
            <el-form-item label="文库标签:">
                <el-select :popper-append-to-body="false" filterable remote v-model="form.topic" multiple allow-create
                    default-first-option placeholder="请输入标签名称" @change="onChange" :remote-method="getInput"
                    width="100px" @visible-change="isopen">
                    <el-option v-for="item in topic" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                    <el-option disabled class="load-more" v-if="showMore">
                        <span @click="load2">加载更多...</span>
                    </el-option>
                </el-select>

                <!-- <el-select filterable v-model="form.topic" multiple placeholder="请输入标签">
                    <el-option v-for="item in topic" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select> -->
            </el-form-item>
            <div class="select" v-show="type == 1">
                <el-form-item>
                    <div class="edit" style="">
                        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig"
                            :mode="mode" />
                        <Editor style="height:500px; overflow-y: hidden;" v-model="html" :defaultConfig="editorConfig"
                            :mode="mode" @onCreated="onCreated" />
                    </div>
                </el-form-item>
            </div>

            <el-form-item>
                <div class="btns">
                    <el-button type="primary" @click="onSubmit">提交</el-button>
                </div>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
import { baseUrl } from '@/apis/index'
import axios from 'axios';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
export default {
    components: { Editor, Toolbar },
    data() {
        return {
            filename: '',
            audioname: '',
            videoname: '',
            txt: '',
            url: '',
            cols: [],
            form: {
                title: '',
                topic: [],
                price: 0,
                col_id: ''
            },
            type: 1,
            editor: null,
            html: '',
            toolbarConfig: {
                excludeKeys: [
                    'insertLink',
                    'group-video',
                    'fullScreen'

                ]
            },
            editorConfig: {

            },
            mode: 'default', // or 'simple'


            totalPaget: 1,
            pageNumt: 1,
            topic: [],
            t_keyword: '',
            loadingt: false,
            newlist: [], // 请求参数数组
            choose: [], // 已选标签数组
            old_list: [], // 已绑定标签选择列表
            showMore: false,

            totalPagec: 1,
            pageNumc: 1,
            c_keyword: '',
            loadingc: false,
            showMore1: false
        }
    },
    created() {

        this.editorConfig = {
            MENU_CONF: {
                uploadImage: {
                    server: baseUrl + "user/Upload/one",
                    headers: {
                        'xx-token': localStorage.getItem('token'),
                        'xx-device-type': 'web'
                    },
                    fieldName: 'file',
                    onBeforeUpload(file) {
                        console.log(file);

                        return file


                    },
                    onSuccess(file, res) {          // JS 语法
                        console.log(`${file.name} 上传成功`, res)
                    },
                    customInsert(res, insertFn) {
                        insertFn(res.data.url)
                    }
                },
            }
        }
    },

    mounted() {

        // 监听 selectionchange 事件
        document.addEventListener('selectionchange', this.handleSelectionChange);
        let id = parseInt(this.$route.query.id)
        let aid = parseInt(this.$route.query.aid)

        if (id) {
            this.form.col_id = id
        }

        if (aid) {
            this.form.id = aid
            this.getInfo(aid)
        }
        this.getCols()
    },

    methods: {
        // 关闭列表的时候
        isopen1(e) {
            if (!e) {
                this.reset1()
            }
        },

        reset1() {
            this.totalPagec = 1,
                this.pageNumc = 1,
                this.loadingc = false,
                this.c_keyword = '',
                this.showMore1 = false
            this.cols = []
        },

        loadc() {
            var page = this.pageNumc
            //如果请求未结束就返回不连续请求
            if (this.loadingc) {
                return
            }
            //数据请求完成无更多数据时
            if (page >= this.totalPagec) {
                return false;
            }
            page = parseInt(page) + 1
            this.pageNumc = page
            this.getCols()
        },

        getInput1(keyword) {
            this.topic = this.old_list
            if (!keyword) {
                this.reset1()

                return;
            }
            this.c_keyword = keyword
            this.getCols()
        },


        // 绑定专栏列表
        getCols() {
            this.loadingc = true

            let params = {
                page: this.pageNumc
            }
            this.$api.getCols(params).then(res => {
                if (res.data.code == 1) {
                    let response = res.data.data
                    this.totalPagec = response.last_page
                    if (this.totalPagec <= this.pageNumc) {
                        this.showMore1 = false
                    } else {
                        this.showMore1 = true
                    }
                    this.cols = this.cols.concat(response.data)
                    this.loadingc = false

                    // this.cols = res.data.data
                }
            })
        },

        // getCols() {
        //     this.loadingc = true
        //     let params = {
        //         keyword: this.c_keyword,
        //         page: this.pageNumc,
        //         id: this.form.col_id
        //     }

        //     this.$api.searchColumn(params).then(res => {
        //         let response = res.data.data
        //         if (res.data.code == 1) {
        //             this.totalPagec = response.last_page
        //             if (this.totalPagec <= this.pageNumc) {
        //                 this.showMore1 = false
        //             } else {
        //                 this.showMore1 = true
        //             }
        //             this.loadingc = false
        //             this.cols = this.cols.concat(response.data);

        //         }
        //     })
        // },



        reset() {

            this.totalPaget = 1,
                this.pageNumt = 1,
                this.loadingt = false,
                this.t_keyword = '',
                this.showMore = false
            this.topic = []
        },
        // 关闭列表的时候
        isopen(e) {
            if (!e) {
                this.reset()
            }
        },
        load2() {
            var page = this.pageNumt
            //如果请求未结束就返回不连续请求
            if (this.loadingt) {
                return
            }
            //数据请求完成无更多数据时
            if (page >= this.totalPaget) {
                return false;
            }
            page = parseInt(page) + 1
            this.pageNumt = page
            this.getTopic()
        },

        getInput(keyword) {
            this.topic = this.old_list
            if (!keyword) {
                this.reset()

                return;
            }

            this.t_keyword = keyword
            this.getTopic()

        },

        // select选中后
        onChange(e) {
            // 重做选中的标签数组

            this.newlist = e.map(item => {
                return typeof item === 'string' ? { name: item } : { id: item };
            });
        },

        // 标签库
        getTopic() {
            this.loadingt = true
            let params = {
                keyword: this.t_keyword,
                page: this.pageNumt,
                ids: this.ids
            }

            this.$api.searchTopic(params).then(res => {
                let response = res.data.data
                if (res.data.code == 1) {
                    this.totalPaget = response.last_page
                    if (this.totalPaget <= this.pageNumt) {
                        this.showMore = false
                    } else {
                        this.showMore = true
                    }
                    if (this.ids && !this.keyowrd) {
                        this.old_list = response.data
                        console.log('old_list', this.old_list)

                    }

                    this.loadingt = false
                    this.topic = this.topic.concat(response.data);

                }
            })
        },

        // 文库详情
        getInfo(id) {
            let params = {
                id
            }
            this.$api.getArtInfo(params).then(res => {
                let response = res.data.data
                if (res.data.code == 1) {
                    this.form = response
                    this.html = response.content
                    this.type = response.op
                    let urlname = response.url_name
                    if (this.type == 2) {
                        this.videoname = urlname
                    }

                    if (this.type == 3) {
                        this.audioname = urlname
                    }

                    if (this.type == 4) {
                        this.filename = urlname
                    }

                    if (this.form.topic) {
                        this.ids = this.form.topic
                        this.getTopic()
                    }
                }
            })
        },


        onCreated(editor) {
            this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
        },
        // 音频上传
        onUpload_aduio: function (e) {
            var that = this;
            var file = e.target.files[0];
            var formdata = new FormData();
            formdata.append("file", file, file.name) //通过append向form对象添加
            let config = {
                headers: {
                    "Content-Type": "multipart/form-data",
                    'xx-token': localStorage.getItem('token'),
                    'xx-device-type': 'web'
                }
            }
            axios.post(baseUrl + "user/upload/audio", formdata, config).then(function (res) {
                that.$message({
                    message: res.data.msg
                })
                that.audioname = res.data.data.filename
                that.videoname = ''
                that.filename = ''

                that.url = res.data.data.filepath
            }).catch(function (error) {
                that.$message({
                    message: '请求异常'
                })
                console.log("error", error);
                return false;
            })
        },
        // 视频上传
        onUpload_video: function (e) {
            var that = this;
            var file = e.target.files[0];
            var formdata = new FormData();
            formdata.append("file", file, file.name) //通过append向form对象添加
            let config = {
                headers: {
                    "Content-Type": "multipart/form-data",
                    'xx-token': localStorage.getItem('token'),
                    'xx-device-type': 'web'
                }
            }
            axios.post(baseUrl + "user/upload/video", formdata, config).then(function (res) {
                that.$message({
                    message: res.data.msg
                })
                that.videoname = res.data.data.filename
                that.audioname = ''
                that.filename = ''
                that.url = res.data.data.filepath
            }).catch(function (error) {
                that.$message({
                    message: '请求异常'
                })
                console.log("error", error);
                return false;
            })
        },
        //文件上传
        onUpload_file: function (e) {
            var that = this;
            var file = e.target.files[0];
            var formdata = new FormData();
            formdata.append("file", file, file.name) //通过append向form对象添加
            let config = {
                headers: {
                    "Content-Type": "multipart/form-data",
                    'xx-token': localStorage.getItem('token'),
                    'xx-device-type': 'web'
                }
            }
            axios.post(baseUrl + "user/upload/file", formdata, config).then(function (res) {
                that.$message({
                    message: res.data.msg
                })
                that.filename = res.data.data.filename
                that.audioname = ''
                that.videoname = ''
                that.url = res.data.data.filepath
            }).catch(function (error) {
                that.$message({
                    message: '请求异常'
                })
                console.log("error", error);
                return false;
            })
        },

        getType(i) {
            this.type = i
            this.url = ''
            this.filename = ''
            this.videoname = ''
            this.aduioname = ''
            this.txt = ''
        },
        handleAvatarSuccess(res, file) {
            console.log(file.raw);
            this.form.imageUrl = URL.createObjectURL(file.raw);
        },
        beforeAvatarUpload(file) {
        },
        onSubmit() {
            this.form.content = this.html
            this.form.op = this.type
            this.form.url = this.url
            this.form.topic = this.newlist

            let params = this.form

            this.$api.addArticle(params).then(res => {
                if (res.data.code == 1) {
                    let id = res.data.data
                    this.$message({
                        message: res.data.msg,
                        type: 'success'
                    })

                    this.$router.push({
                        path: '/knowledge/library'
                    })

                    // this.$router.back()
                }
            })
        }
    }
}
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="scss" scoped>
.outer {
    height: 100%;
    overflow-y: auto;
    -ms-overflow-style: none;

    &::-webkit-scrollbar {
        /*滚动条整体样式*/
        width: 0 !important;
        /*高宽分别对应横竖滚动条的尺寸*/
        height: 0 !important;
    }
}

.types {
    display: flex;

    i {
        margin-right: 0.73rem;
        font-size: 32px;
    }
}

.type {
    cursor: pointer;
    width: 8.8rem;
    height: 3.18rem;
    margin-right: 1.35rem;
    background: #FFFFFF;
    border-radius: 0.31rem;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 400;
    font-size: 1.04rem;
    color: #000000;
    border: 1px solid #ccc;

    .tIcon {
        height: 1.46rem;
        width: auto;
        margin-right: 0.73rem;
    }

    .rIcon {
        position: absolute;
        right: 0;
        top: 0;
        width: 1.3rem;
        height: 1.25rem;
    }
}

.active {
    color: #1068E7;
    border: 1px solid #1068E7;

    i {
        color: #1068E7;
    }
}

.upload {
    display: flex;

    label {
        margin-right: 3rem;
        text-align: center;
        white-space: nowrap;
        cursor: pointer;
        font-size: 1rem;
        color: #1a1a1a;

        input[type=file] {

            display: none;
            opacity: 0;
        }

        img {
            display: block;
            margin: 0 auto 0.8rem;
        }
    }
}
.edit{
    border: 1px solid #ccc;width: 1100px;
}
</style>